package com.service;


import cn.hutool.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class MailService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender  javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送验证码到指定邮件
     * @param to
     */
    public void sendMail(String to)
    {
        //产生验证码
        String code = RandomUtil.randomString(4);

        //保存到redis
        redisTemplate.boundZSetOps("mail").add(to+":"+code,System.currentTimeMillis());

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject("验证码");
        simpleMailMessage.setText("您的验证码是:"+code);
        javaMailSender.send(simpleMailMessage);
    }

    /**
     * 验证验证码是否正确
     * @param to  接收
     * @param code 验证码
     * @return
     */
    public boolean checkCode(String to, String code)
    {
        //Long minchi = redisTemplate.boundZSetOps("mail").rank(to+":"+code);
        Long minchi = redisTemplate.opsForZSet().rank("mail",to+":"+code);
        if (minchi==null)
        {
            return false;
        }
        //存在还要删除
        redisTemplate.boundZSetOps("mail").removeRange(minchi,minchi);
        //redisTemplate.boundZSetOps("mail").remove(to+":"+code);

        return true;
    }

}
